<template>
  <div class="apple-header" v-if="data">
    <!-- 顶部导航栏以及登录设置 -->
    <div class="top-nav">
      <!-- 版心980px -->
      <div class="top-center">
        <ul id="navList" class="nav-ul">
          <li>
            <router-link
              to="/"
              class="nav-icon nav-link-apple"
              :style="`backgroundImage: url(${encodeImgUrl(
                'global_apple_image.svg'
              )}`"
            >
              <span></span
            ></router-link>
          </li>
          <li><router-link to="/store">商店</router-link></li>
          <li><router-link to="/mac">Mac</router-link></li>
          <li><router-link to="/ipad">iPad</router-link></li>
          <li><router-link to="/iphone">iPhone</router-link></li>
          <li><router-link to="/watch">Watch</router-link></li>
          <li><router-link to="/airpods">AirPods</router-link></li>
          <li><router-link to="/family">家居</router-link></li>
          <li><router-link to="/airtag">airTag</router-link></li>
          <li><router-link to="/parts">配件</router-link></li>
          <li><router-link to="/support">技术支持</router-link></li>
          <li><router-link to="/shoplist">全部商品</router-link></li>

          <li>
            <a
              @click="search"
              class="nav-icon nav-link-search"
              :style="`backgroundImage: url(${encodeImgUrl(
                'global_search_image.svg'
              )}`"
            >
              <span></span>
            </a>
          </li>

          <li class="shoppBag">
            <a
              @click="shopbag"
              class="nav-icon nav-link-bag"
              :style="`backgroundImage: url(${encodeImgUrl(
                'global_bag_image.svg'
              )}`"
            >
              <span></span>
              <span class="prodectNum" v-if="userShopbagData">{{
                shopbagLength
              }}</span>
            </a>
            <!-- 购物袋 -->
            <div
              class="shoppBag-box"
              id="shoppBagBox"
              style="display: none"
              @click="shopbagBuble"
            >
              <div class="bag-view">
                <p v-if="!userShopbagData">你的购物袋是空的</p>
                <ul class="bag-prodect-list" v-else>
                    <li v-for="(pro,i) in maxBagLength" 
                    :key="i"
                    >
                        <img :src="userShopbagData[i].img" />
                        <p :title="`${userShopbagData[i].title}`">{{userShopbagData[i].title}}</p>
                        <span class="bag-prodect-li-num">{{userShopbagData[i].num}}个</span>
                    </li>
                </ul>
                <div v-if="userShopbagData && userShopbagData.length>=4" style="margin-bottom:10px">
                    <span>最多只显示4条数据</span>
                </div>
                <div v-if="userShopbagData&&userShopbagData.length>0" class="ckeckPlace-box">
                    <button class="ckeckPlace"
                    @click="linktopage('/shoppingcart')"
                    
                    >结账</button>
                </div>
            
                <div class="bag-nav">
                  <ul class="bag-nav-ul">
                    <li>
                      <a
                        class="bag-nav-baglink"
                        :style="`backgroundImage: url(${encodeImgUrl(
                          'bag.svg'
                        )}`"
                        @click="linktopage('/shoppingcart')"
                        >
                            <span v-if="userShopbagData">购物袋{{`（
                            ${shopbagLength} ）`}}</span>
                            <span v-else>购物袋</span>
                        </a
                      >
                    </li>
                    <!-- <li>
                                            <a href="" class="bag-nav-collect"
                                            :style="`backgroundImage: url(${encodeImgUrl('savedbyyou.svg')}`"
                                                >收藏商品</a
                                            >
                                        </li> -->
                    <li v-if="!userData">
                      <a
                        class="bag-nav-orders"
                        :style="`backgroundImage: url(${encodeImgUrl(
                          'orders.svg'
                        )}`"
                        @click="linktopage('/register')"
                        >注册</a
                      >
                    </li>
                    <!-- 账户 -->
                    <!-- <li>
                      <a
                        href=""
                        class="bag-nav-account"
                        :style="`backgroundImage: url(${encodeImgUrl(
                          'account.svg'
                        )}`"
                        >账户</a
                      >
                    </li> -->
                    <li>
                      <a
                        @click="loginOrDelete"
                        class="bag-nav-singin"
                        :style="`backgroundImage: url(${encodeImgUrl(
                          'signIn.svg'
                        )}`"
                        >{{
                          userData == "" || !userData
                            ? "登录"
                            : "注销 " + userData.username
                        }}</a
                      >
                    </li>
                    <!-- <li>
                                            <a @click="linktopage('/shoplist')" class="bag-nav-singin"
                                            :style="`backgroundImage: url(${encodeImgUrl('savedbyyou.svg')}`"
                                                >全部商品</a
                                            >
                                        </li> -->
                  </ul>
                </div>
              </div>
            </div>
          </li>
        </ul>
      </div>
    </div>

    <!-- 搜索的遮罩层 -->
    <div class="masked" id="mask_id">
      <div class="search-box">
        <div class="search-head" id="searchHead">
          <span
            class="sreach-img"
            :style="`backgroundImage: url(${encodeImgUrl(
              'global_search_image.svg'
            )}`"
          ></span>
          <input
            type="text"
            name="search"
            id="searchInput"
            placeholder="搜索 apple.com.cn"
            v-model="searchString"
            @keydown.enter="toSearching"
          />
          <span
            class="sreach-img2"
            id="searchClose"
            @click="showNav"
            :style="`backgroundImage: url(${encodeImgUrl('close.png')}`"
          ></span>
        </div>

        <div class="search-text" id="searchText">
          <div v-if="!isOkSearchStr">没有内容 请搜索正确的商品名字</div>
          <div v-if="isOkSearchStr && searchData">
            <div id="fastSearch">
              <h3>快速链接</h3>
              <ul>
                <li v-for="{toListTitle,linkto,id} in searchData"
                :key="id">
                      <a @click="linktopage('/'+linkto)">{{toListTitle}}</a>
                </li>
              </ul>
              <span></span>
					  </div>
          </div>
          <!-- fastSearch是之后的页面，通过输入要搜索的物品达到快速搜索的目的 -->
          <!-- 				<div id="fastSearch">
						<h3>快速链接</h3>
						<ul>
							<li><a href="">配件</a></li>
							<li><a href="">AirPods</a></li>
							<li><a href="">AirTag</a></li>
							<li><a href="">iphnoe</a></li>
							<li><a href="">Mac</a></li>
						</ul>
						<span></span>
					</div> -->
          <h3>搜索建议</h3>
          <ul>
            <li><a @click="linktopage('/parts')">配件</a></li>
            <li>
              <a @click="linktopage('/airpods')">AirPods</a>
            </li>
            <li><a @click="linktopage('/airtag')">AirTag</a></li>
            <li><a @click="linktopage('/iphone')">iphnoe</a></li>
            <li><a @click="linktopage('/mac')">Mac</a></li>
          </ul>
        </div>
      </div>
    </div>
  </div>
</template>

<script>
import axios from "axios";
export default { 
  data() {
    return {
      data: null,
      userData: null,
      userShopbagData: null,
      maxBagLength:0,
      searchString:'',
      isOkSearchStr:false,
      searchData:null

      // shopbagLength:0,
    };
  },
  methods: {
    //搜索函数 
    toSearching(){
      if(this.searchString == ''){
        this.isOkSearchStr = false
        return
      }else{
        let searchUrl = `http://localhost:3000/product?q=${this.searchString}`
        axios.get(searchUrl)
        .then(res=>{
          // if(res.data = []){return;}
          this.searchData = res.data;
          this.isOkSearchStr = true;
          console.log(res.data)
        })
      }
    },
    linktopage(path) {
      // this.shopbag()
      if (this.$route.path == path) {
        // this.$router.go(0);
        this.showNav();
        return;
      }
      this.showNav();
      this.$router.push(path);
    },
    //登录 or 注销
    loginOrDelete() {
      this.showNav();
      if (this.userData == "" || !this.userData) {
        // 去登录
        if(this.$route.path == '/login'){
            //如果就在登录页面的话 就什么也不做 
            //顺便刷新下页面
            this.$router.go(0)
        }
        else{
            this.$router.push('/login');
        }
      }
      else{
        //注销账号 清空浏览器的user数据
        window.sessionStorage.removeItem('user');
        //并且删除所有用户设定的内容
        this.userData = null;
        this.userShopbagData = null;
        this.maxBagLength = 0
        if(this.$route.path =='/shoppingcart'){
          this.$router.push('/login');
        }
      }
        
    },
    search() {
      // 点击搜索时，消失nav的内容
      navList.style.opacity = 0;

      // navList.style = "visibility: hidden;"
      //显示遮罩层里的内容
      mask_id.style = "display:block";

      let tempTimer = setTimeout(() => {
        searchHead.style["margin-left"] = 0;
        searchHead.style.opacity = 1;
        searchHead.style.transform = "scale(1)";
        // 默认获得焦点
        searchInput.focus();
        searchText.style.opacity = 1;
        clearTimeout(tempTimer);
      }, 200);
    },
    showNav() {
      this.searchData = null;
      this.isOkSearchStr = false;
      // 点击关闭的时候就会重新显示nav
      mask_id.style = "display:none";
      navList.style = "visibility: visible;";
      // 点击关闭的时候清空input里的内容，如果有的话
      searchInput.value = "";
      searchText.style.opacity = 0;
      // 将搜索头部归位
      searchHead.style["margin-left"] = "100%";
      searchHead.style.opacity = 0;
      searchHead.style.transform = "scale(0)";

      // 然后关闭一下商品背包的标签
      shoppBagBox.style.display = "none";
    },
    // 购物背包的点击，显示和消失效果
    shopbag(e) {
      if (shoppBagBox.style.display == "none") {
        shoppBagBox.style.display = "block";
      } else {
        shoppBagBox.style.display = "none";
      }
      e.stopPropagation();
      // this.stopFunc(shoppBagBox);
    },
    //购物背包的阻止事件冒泡
    shopbagBuble(e) {
      e.stopPropagation();
    },
    getImgData() {
      let url = "http://localhost:3000/HYLImg";
      axios
        .get(url)
        .then((res) => {
          return res.data;
        })
        .then((d) => {
          this.data = d;
        });
    },
    getUserData() {
      let user = window.sessionStorage.getItem("user");

      //   如果user存在但是没有值的情况下
      //   如果user根本不存在的情况下
      if (user == "" || !user) {
        //未登录
        return;
      }

      //    解析浏览器的user数据，原本是json字符串，换算成js对象
      user = JSON.parse(user);
      this.userData = user; //用户信息已经拿到了,接下来是拿到用户购物袋的信息

      let url = `http://localhost:3000/shopBagList?userId=${this.userData.id}`;
      axios.get(url).then((res) => {
        //加强判断 防止错误数据进入页面
        //如果用户购物袋为空的情况下 userShopbagData 还是为默认值 null
        this.maxBagLength = res.data.length
        if (res.data.length == 0) {
          this.userShopbagData = null
          return;
        }else if(res.data.length>=4){
            //重设最大显示数量
            this.maxBagLength = 4
        }
        this.userShopbagData = res.data;
      });

      //   console.log();
    },
  },
  computed: {
    encodeImgUrl() {
      return function (imgName) {
        // console.log(this.data["room_filling_sound.jpg"])
        return this.imgBaseUrl + this.data[imgName];
      };
    },
    shopbagLength() {
      let sum = 0
      this.userShopbagData.forEach(e => {
        sum+=e.num
        // console.log(e.num)
      });
      return sum
    }
  },
  mounted() {
    this.getImgData();
    this.getUserData();
    // clearInterval(userInterval);
    let userInterval = setInterval(()=>{
      this.getUserData()
    }, 2500);
  },
};
</script>

<style scoped>
.apple-header {
  background-color: #f5f5f7;
  font-size: 12px;
}
ul,
ol,
a,
a:link {
  text-decoration: none;
  list-style: none;
  /* color: #1D1D1F; */
}
ul {
  margin: 0;
}
input {
  outline: none;
}
/* 顶部导航栏样式 */
.top-nav {
  background-color: #000000cc;
  height: 44px;
  /* width: 100vw; */
  min-width: 980px;
  /* 	position: fixed; */
  z-index: 222;
}

/* 顶部导航栏版心 */
.top-center {
  width: 980px;
  margin: 0 auto;
}

/* 对nav的ul进行弹性布局 */
.top-center .nav-ul {
  display: flex;
  justify-content: space-between;
  align-items: center;
  flex-wrap: nowrap;
  opacity: 1;
  /* visibility: visible; */
  transition: 0.5s;
}

.top-center .nav-ul > li > a {
  color: #f5f5f7;
  display: block;
  line-height: 44px;
  padding: 0 8px;
  opacity: 0.7;
  background-repeat: no-repeat;
}

/* 设置停留变色的效果 */
.top-center .nav-ul li a:hover {
  opacity: 1;
}

/* 小苹果图标 */
.nav-link-apple {
  background-size: 14px 44px;
  background-position: center center;
  width: 14px;
}

/* 搜索放大镜图标 */
.nav-link-search {
  background-size: 15px 88px;
  background-position: 8px 0;
  width: 15px;
}

/* 购物袋图标 */
.nav-link-bag {
  background-size: 13px 44px;
  width: 13px;
  background-position: center center;
  cursor: pointer;
}

.nav-icon span {
  width: 1px;
  height: 1px;
  display: inline-block;
}

/* 遮罩层 */
.masked {
  background-color: rgba(0, 0, 0, 0.7);
  /* 使用固定定位撑满全屏 */
  position: fixed;
  /* 使得撑满全屏，四个位置都是0 */
  top: 0;
  bottom: 0;
  left: 0;
  right: 0;
  display: none;
  z-index: 997;
}

/* 遮罩层里的搜索内容 */
.masked .search-box {
  width: calc(980px * 0.66);
  height: 538px;
  /* background-color: white; */
  text-align: center;
  position: absolute;
  /* 当一个明确宽高的子元素绝对定位,使用margin auto实现在父元素里的水平垂直居中 */
  top: 0;
  bottom: 0;
  left: 0;
  right: 0;
  margin: 0 auto;
}

.search-head {
  /* display: flex; */
  /* justify-content: space-around; */
  height: 44px;
  position: relative;

  opacity: 0;
  transform: scale(0);
  margin-left: 100%;
  transition: 0.6s;
}

.search-head input {
  border: 0;
  /* border-radius: 20px; */
  padding: 0 38px 0 40px;
  height: 100%;
  width: 100%;
  box-sizing: border-box;
  background-color: rgba(0, 0, 0, 0.7);

  color: white;
  font-size: 16px;
  overflow: hidden;
}

.search-head .sreach-img {
  display: inline-block;
  height: 44px;
  width: 40px;
  background-repeat: no-repeat;
  background-size: 15px 88px;
  background-position: 12.5px -44px;

  position: absolute;
  top: 0;
  left: 0;
}

.search-head .sreach-img2 {
  display: inline-block;
  cursor: pointer;
  height: 22px;
  width: 22px;
  opacity: 0.6;
  background-repeat: no-repeat;
  background-position-x: center;
  background-position-y: center;
  transform: rotate(45deg);

  position: absolute;
  color: #86868b;
  top: 11px;
  right: 0;
}

.search-text {
  background-color: white;
  width: 100%;
  border-bottom-left-radius: 18px;
  border-bottom-right-radius: 18px;
  text-align: left;
  padding: 10px 10px;
  box-sizing: border-box;
  opacity: 0;
  transition: 1s;
}

.search-text h3 {
  font-size: 12px;
  color: #6e6e73;
  margin-left: 20px;
  margin-top: 23px;
  font-weight: 300;
}

.search-text span {
  border-top: 1px solid #d2d2d7;
  display: block;
  width: 100%;
}

.search-text ul {
  padding-top: 5px;
  padding-bottom: 15px;
}

.search-text ul li:hover {
  background-color: #f5f5f7;
}

.search-text ul li a {
  display: block;
  font-size: 14px;
  line-height: 2.5;
  padding: 0 48px;
  color: #6e6e73;
  cursor: pointer;
}

.shoppBag {
  position: relative;
  user-select: none;
  z-index: 999;
}
.shoppBag .prodectNum {
  position: absolute;
  top: 20px;
  width: 18px;
  height: 18px;
  display: block;
  left: 12px;
  background-color: #f5f5f7;
  border-radius: 50%;
  color: #000000cc;
  text-align: center;
  line-height: 18px;
}
.ckeckPlace{
    background-color: #06c;
    border: 0;
    border-radius: 10px;
    color: #fff;
    padding: 8px 16px;
    flex: 1;
    text-align: center;
    font-size: 17px;
    cursor: pointer;

}
.ckeckPlace-box{
    width: 100%;
    display: flex;
    justify-content: center;
    margin-bottom: 10px;
}
.bag-prodect-list{
    display: flex;
    flex-direction: column;
    justify-content: center;
    align-items: center;
    padding: 0;
    font-size: 14px;
    color: #1d1d1f;
}
.bag-prodect-list li{
    display: flex;
    /* justify-content: space-between; */
    align-items: center;
    width: 100%;
    height: 60px;
    padding: 16px 0;
    border-top: 1px solid #d2d2d7;
    position: relative;
}
.bag-prodect-list p{
    margin: 0;
    text-align:left;
    overflow: hidden;
    text-overflow: ellipsis;
    display: -webkit-box;
    -webkit-line-clamp: 2;
    -webkit-box-orient: vertical;
    /* white-space: nowrap; */
}
.bag-prodect-list img{
    max-width: 60px;
    min-width: 60px;
    height: 60px;
    padding-right: 5px;
}
.bag-prodect-li-num{
    position: absolute;
    bottom: 0;
    right: 0;
}
.doubleNum {
  width: 20px;
  line-height: 20px;
  height: 20px;
}
.shoppBag-box {
  /* height: 322px; */
  width: 286px;
  border: 1px solid #d2d2d7;
  border-radius: 18px;
  position: absolute;
  top: 100%;
  left: -125.5px;
  background-color: white;
  z-index: 224;
  /*-webkit-backdrop-filter: saturate(180%) blur(10px);
  backdrop-filter: saturate(180%) blur(10px);
  background-color: rgba(255,255,255, 0.2);*/
}

.bag-view {
  margin: 0 auto;
  padding: 0 20px;

}

.bag-view > p {
  padding: 35px 0 23px;
  margin: 0;
  text-align: center;
  font-size: 14px;
  color: #6e6e73;
}

.bag-nav {
  margin-bottom: 9px;
  cursor: pointer;
}

.bag-nav-ul {
  margin-top: 12px;
  margin: 0;
  padding: 0;
}

.bag-nav-ul li {
  border-top: 1px solid #d2d2d7;
}

.bag-nav-ul li a {
  font-size: 14px;
  color: #06c;
  display: block;
  line-height: 44px;
  padding: 0 28px;
  overflow: hidden;

  background-repeat: no-repeat;
  background-position: -2px 11px;
  background-size: 21px 21px;
}

.bag-nav-ul li a:hover {
  text-decoration: underline;
}
</style>